const Mock = require('mockjs')
const { find: findOrgUnit } = require('./org-units')
const { find: findRoom, list: listRoom } = require('./rooms')

const ChargeRecords = []
let id = 1
const roomPage = listRoom(1, 30)
for (let i = 0; i < roomPage.data.records.length; ++i) {
  const r = roomPage.data.records[i]
  if (!r) continue
  const org = findOrgUnit(r.orgUnitId)
  ChargeRecords.push(Mock.mock({
    id: id++,
    orgUnitId: org.id,
    roomId: r.id,
    prepareDate: Mock.Random.datetime(),
    payType: (i % 2) + 1,
    state: (i % 3) + 1,
    amount: i * 100,
    endTime: Mock.Random.datetime()
  }))
}

function list(page, limit, orgUnitId, roomId) {
  limit = Math.max(1, Math.min(parseInt(limit), 50))
  page = Math.max(parseInt(page), 1)
  orgUnitId = orgUnitId ? parseInt(orgUnitId) : null
  roomId = roomId ? parseInt(roomId) : null
  let mocks = ChargeRecords.filter(item => {
    if (roomId && roomId !== item.roomId) return false
    return !(orgUnitId && item.orgUnitId !== orgUnitId)
  })
  const total = mocks.length
  mocks = mocks.filter((u, index) => index < limit * page && index >= limit * (page - 1))
  mocks = mocks.map(d => {
    const o = findOrgUnit(d.orgUnitId)
    const r = findRoom(d.roomId)
    return { ...d, orgUnitName: o ? o.name : '', roomName: r ? r.name : '' }
  })
  return { success: true, data: { total: total, records: mocks }}
}

function save(roomId, amount, payType) {
  roomId = roomId ? parseInt(roomId) : null
  amount = amount ? parseInt(amount) : null
  payType = payType ? parseInt(payType) : null
  const r = findRoom(roomId)
  ChargeRecords.push(Mock.mock({
    id: ChargeRecords[ChargeRecords.length - 1].id + 1,
    orgUnitId: r.orgUnitId,
    roomId: roomId,
    prepareDate: new Date(),
    payType: payType,
    state: payType === 3 ? 2 : 1,
    amount: amount,
    endTime: payType === 3 ? new Date() : null
  }))
  if (payType === 3) {
    r.balance += amount
  }
  return ChargeRecords[ChargeRecords.length - 1].id
}

function find(id) {
  id = id ? parseInt(id) : null
  for (let i = 0; i < ChargeRecords.length; ++i) {
    if (ChargeRecords[i].id === id) {
      const d = ChargeRecords[i]
      const o = findOrgUnit(d.orgUnitId)
      const r = findRoom(d.roomId)
      return { ...d, orgUnitName: o ? o.name : '', roomName: r ? r.name : '' }
    }
  }
  return null
}

function close(id) {
  id = id ? parseInt(id) : null
  for (let i = 0; i < ChargeRecords.length; ++i) {
    if (ChargeRecords[i].id === id) {
      const d = ChargeRecords[i]
      d.state = 3
      d.endTime = new Date()
    }
  }
}

module.exports = { list, save, find, close }
